package com.ruoyi.base.utils.aes;

import com.ruoyi.base.exception.SysException;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES
 *
 * @author lcf
 */
public class AesUtils {
    /**
     * 密钥长度
     */
    private static int keyLength = 16;

    /**
     * 加密
     *
     * @param sSrc 明文
     * @param sKey 密钥
     */
    public static String encrypt(String sSrc, String sKey) {
        try {
            checkKey(sKey);

            SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(StandardCharsets.UTF_8), "AES");
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

            return Base64.getUrlEncoder().encodeToString(cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     *
     * @param sSrc 密文
     * @param sKey 密钥
     */
    public static String decrypt(String sSrc, String sKey) {
        try {
            checkKey(sKey);

            SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);

            return new String(cipher.doFinal(Base64.getUrlDecoder().decode(sSrc.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 检查密钥合法性
     *
     * @param key 密钥
     */
    private static void checkKey(String key) {
        // 判断Key是否正确
        if (StringUtils.isBlank(key)) {
            throw new SysException("AES密钥为空");
        }
        // 判断Key是否为16位
        if (key.length() != keyLength) {
            throw new SysException("AES密钥长度不合法");
        }
    }

    public static void main(String[] args) {
        /*
         * 此处使用AES-128-ECB加密模式，key需要为16位。
         */
        String cKey = "jkl;POIU1234++==";
        // 需要加密的字串
        String cSrc = "URL变体修改的Base64";

        // 加密
        String enString = AesUtils.encrypt(cSrc, cKey);
        System.out.println("加密后的字串是：" + enString);

        // 解密
        String deString = AesUtils.decrypt(enString, cKey);
        System.out.println("解密后的字串是：" + deString);
    }
}